<template>
  <div class="app-container" v-loading="loading">
    <el-descriptions :column="3" border>
      <el-descriptions-item label="任务名称">{{detailData.task?detailData.task.taskName:""}}</el-descriptions-item>
      <el-descriptions-item label="税源地">{{detailData.taxCompanyName}}</el-descriptions-item>
      <el-descriptions-item label="类型">
        <el-tag type="success" v-if="detailData.task.type === 1">分包</el-tag>
        <el-tag v-else-if="detailData.task.type === 2">众包</el-tag>
      </el-descriptions-item>

      <el-descriptions-item label="打款金额">{{ detailData.amount}}元</el-descriptions-item>
      <el-descriptions-item label="总服务费">{{ detailData.serviceAmount }}元</el-descriptions-item>
      <el-descriptions-item label="打款充值金额">{{ detailData.totalAmount }}元</el-descriptions-item>
      <el-descriptions-item label="总人数">{{ detailData.totalNum }}人</el-descriptions-item>
      <el-descriptions-item label="成功人数">{{ detailData.successNum }}人</el-descriptions-item>
      <el-descriptions-item label="下发成功金额">{{ detailData.successAmount }}元</el-descriptions-item>
      <el-descriptions-item label="个人费率">{{ detailData.staffRate }}%（{{detailData.staffAmount}}元）</el-descriptions-item>
      <el-descriptions-item label="企业费率">{{ detailData.merchantRate }}%（{{detailData.merchantAmount}}元）</el-descriptions-item>
      <el-descriptions-item label="总费率">{{ detailData.totalRate }}%</el-descriptions-item>
      <el-descriptions-item label="打款状态">
        <el-tag type="info" v-if="detailData.status === 0">初始化</el-tag>
        <el-tag type="warning" v-else-if="detailData.status === 1">打款中</el-tag>
        <el-tag v-else-if="detailData.status === 2">打款完成</el-tag>
        <el-tag type="warning" v-else-if="detailData.status === 4">打款部分完成</el-tag>
        <el-popover
          placement="top-start"
          :width="300"
          trigger="click"
          v-else-if="detailData.status === 3"
          :content="detailData.transFailReason">
          <template #reference>
            <el-tag style="cursor: pointer" slot="reference" type="danger">打款失败</el-tag>
          </template>
        </el-popover>
      </el-descriptions-item>
      <el-descriptions-item label="审核状态">
        <el-tag type="info" v-if="detailData.auditStatus === 0">初始化</el-tag>
        <el-tag type="warning" v-else-if="detailData.auditStatus === 1">审核中</el-tag>
        <el-tag v-else-if="detailData.auditStatus === 2">审核通过</el-tag>
        <el-popover
          placement="top-start"
          :width="300"
          trigger="click"
          v-else-if="detailData.auditStatus === 3"
          :content="detailData.auditReason">
          <template #reference>
            <el-tag style="cursor: pointer" slot="reference" type="danger">审核驳回</el-tag>
          </template>
        </el-popover>
      </el-descriptions-item>
      <el-descriptions-item label="申请备注">
        <el-popover
          placement="top-start"
          :width="300"
          trigger="click"
          :content="detailData.reason">
          <template #reference>
            <el-tag style="cursor: pointer" slot="reference" type="success">点击查看</el-tag>
          </template>
        </el-popover>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{detailData.createTime}}</el-descriptions-item>
      <el-descriptions-item label="审核时间">{{detailData.auditTime}}</el-descriptions-item>
      <el-descriptions-item :span="1" label="打款时间">{{detailData.transTime}}</el-descriptions-item>
    </el-descriptions>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="detailData.auditStatus === 0 || detailData.auditStatus === 3"
          type="primary"
          icon="el-icon-position"
          size="mini"
          v-hasPermi="['transfer:payslip:saveToExamine']"
          @click="applyForOpen = true"
        >提交审核</el-button>
      </el-col>
      <el-col :span="1.5" v-if="detailData.auditStatus === 2 && detailData.status === 0">
        <el-button
          type="primary"
          icon="el-icon-position"
          size="mini"
          :disabled="detailData.status !== 0"
          @click="handlePaymentConfirm"
          v-hasPermi="['transfer:payslip:payment']"
        >打款</el-button>
      </el-col>
      <el-col :span="1.5">
        <ImportFile
          @input="handleImport"
          :data="{outBatchNo:detailData.outBatchNo}"
          :file-type="['xlsx']"
          :is-show-tip="false"
          :is-show-file-list="false"
          url="/transfer/payslip/importStaff"
          v-hasPermi="['transfer:payslip:importStaff']"
          :disabled="!(detailData.auditStatus === 0 || detailData.auditStatus === 3)"
        ></ImportFile>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="text"
          size="mini"
          @click="handleDownloadFile('/打款人员模板.xlsx')"
          v-hasPermi="['transfer:payslip:importStaff']"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5" v-if="detailData.receiptUrl">
        <el-button
          type="text"
          size="mini"
          @click="handleDownloadReceiptUrl()"
          v-hasPermi="['transfer:payslip:query']"
        >下载回执单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="text"
          size="mini"
          :disabled="!(detailData.status === 2 || detailData.status === 4)"
          @click="download('transfer/payslip/taskAcceptanceForm/'+detailData.payslipId, {}, `任务验收单_${new Date().getTime()}.pdf`)"
          v-hasPermi="['transfer:payslip:query']"
        >下载任务验收单</el-button>
      </el-col>
    </el-row>
    <el-tabs v-model="activeName" >
      <el-tab-pane label="打款人员" name="payslipDetail">
        <payslip-staff :type="2" @refresh="handlePayslip" ref="payslipDetailRef" v-if="detailData.outBatchNo" :detailPayslipData="detailData"></payslip-staff>
      </el-tab-pane>
      <el-tab-pane label="发票详情" name="invoice">
        <invoiceTask @refresh="handlePayslip" ref="invoiceTaskRef" v-if="detailData.outBatchNo" :detailPayslipData="detailData"></invoiceTask>
      </el-tab-pane>

    </el-tabs>


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="提交审核" :visible.sync="applyForOpen" width="500px" destroy-on-close append-to-body>
      <el-form v-loading="applyForLoading" ref="applyForForm" :model="detailData" label-width="80px">
        <el-form-item label="税源地" prop="tslName">
          {{ detailData.taxCompanyName }}
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          {{ detailData.task?detailData.task.taskName:"" }}
        </el-form-item>
        <el-form-item label="申请备注">
          <el-input v-model="detailData.reason" :autosize="{ minRows: 8, maxRows: 8}" type="textarea" placeholder="请输入申请备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="applyForLoading" type="primary" @click="handleApplyForLoading">提 交</el-button>
        <el-button :loading="applyForLoading" @click="applyForOpen = false">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="打款确认" :visible.sync="paymentOpen" width="800px" destroy-on-close append-to-body>
      <div v-loading="paymentLoading" >
        <el-descriptions :column="3" border>
          <el-descriptions-item label="任务名称">{{detailData.task.taskName}}</el-descriptions-item>
          <el-descriptions-item label="税源地">{{detailData.taxCompanyName}}</el-descriptions-item>

          <el-descriptions-item label="下发金额">{{detailData.amount}}元</el-descriptions-item>
          <el-descriptions-item label="总服务费">{{detailData.serviceAmount}}元</el-descriptions-item>
          <el-descriptions-item label="充值金额">{{detailData.totalAmount}}元</el-descriptions-item>
          <el-descriptions-item label="总人数">{{detailData.totalNum}}人</el-descriptions-item>
          <el-descriptions-item label="账户余额">{{detailData.product?detailData.product.name:""}}({{balance}}元)</el-descriptions-item>

        </el-descriptions>
        <el-form v-loading="applyForLoading" :rules="rules" ref="form" :model="detailData" style="margin-top: 10px" label-width="80px">
          <template v-if="detailData.productId === '8icffqea4enwm3i6zph7yorktvrzdjh9'" >
            <el-form-item label="打款类型" prop="proxyType">
              <el-select v-model="detailData.proxyType" placeholder="请选择打款类型" clearable>
                <el-option
                  v-for="(item,index) in zhTrstyp"
                  :key="index"
                  :label="item.c_trstyp"
                  :value="item.trstyp"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="打款用途" prop="purpose">
              <el-input v-model="detailData.purpose" :autosize="{ minRows: 8, maxRows: 8}" :max="80" type="textarea" placeholder="请输入打款用途"></el-input>
            </el-form-item>

          </template>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="paymentLoading" type="primary" @click="handlePayment">打 款</el-button>
        <el-button :loading="paymentLoading" @click="paymentOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import ImportFile from "@/components/ImportFile/index.vue";
import InvoiceTask from "@/views/transfer/payslip/profile/invoice-task.vue";
import PayslipStaff from "@/views/transfer/payslip/profile/payslip-staff.vue";
import {sumAccountBalance} from "@/api/transfer/transferAccountMerchantBalance";
import {getPayslip, paymentPayslip, saveToExamine, zhTrstyp} from "@/api/transfer/payslip"
import {download} from "@/utils/request";
export default {
  name: 'payslipDetail',
  components: { InvoiceTask, ImportFile, PayslipStaff},
  props:{
    payslipId:{
      type: String,
      default:null
    }
  },
  data(){
    return {
      balance:0,
      zhTrstyp:{},
      loading:false,
      applyForOpen:false,
      paymentOpen:false,
      paymentLoading:false,
      applyForLoading:false,
      activeName:"payslipDetail",
      detailData:{
        task:{},
        product:{}
      },
      rules:{
        proxyType:[
          { required: true, message: "请选择打款类型", trigger: "change" }
        ],
        busmod:[
          // { required: true, message: "请选择业务模式", trigger: "change" }
        ],
        purpose:[
          { required: true, message: "请输入打款用途", trigger: "change" }
        ]
      },
    }
  },
  methods:{
    download,
    handleDownloadFile(filePath){
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
      const day = String(now.getDate()).padStart(2, '0');

      const fileName = `打款人员模板_${year}-${month}-${day}.xlsx`;

      const link = document.createElement('a');
      link.href = filePath;
      link.download = fileName; // 设置格式化后的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleDownloadReceiptUrl(){
      const link = document.createElement('a');
      link.href = process.env.VUE_APP_BASE_API + this.detailData.receiptUrl;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    handlePayslip(val){
      this.loading = true
      if (!val){
        val = this.payslipId
      }
      getPayslip(val).then(res => {
        this.loading = false
        if (res.data){
          this.detailData = res.data;
        }
      }).catch(()=>{
        this.loading = false
      })
    },

    handleImport(){
      this.handlePayslip(this.detailData.payslipId)
      if(this.activeName === 'payslipDetail'){
        this.$refs['payslipDetailRef'].getList();
      }
    },

    handleApplyForLoading(){
      let param = {...this.detailData}
      param.auditStatus = 1
      this.applyForLoading = true
      saveToExamine(param).then(res=>{
        this.applyForOpen = false
        this.applyForLoading = false
        this.$message.success("提交成功")
        this.handlePayslip(this.detailData.payslipId);
      }).catch(()=>{
        this.applyForLoading = false
      })
    },

    handlePaymentConfirm() {

      this.paymentOpen = true
      sumAccountBalance({productId:this.detailData.productId,userType:4,taxOrganizationId:this.detailData.taxOrganizationId,organizationId:this.detailData.merchantOrganizationId}).then(res=>{
        this.balance = res.data?res.data:0
      })
      if (this.detailData.productId === "8icffqea4enwm3i6zph7yorktvrzdjh9") {
        this.paymentLoading = true
        zhTrstyp(this.detailData.outBatchNo).then(res=>{
          this.paymentLoading = false
          this.zhTrstyp = res.data
          this.detailData.proxyType = "BYBK"
        }).catch(()=>{
          this.paymentLoading = false
        })
        this.paymentLoading = true
      }
    },
    handlePayment(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认要打款任务名称为"' + this.detailData.task.taskName + '"的数据？').then(()=>{
            this.paymentLoading = true
            return paymentPayslip(this.detailData)
          }).then(() => {
            this.handlePayslip();
            this.paymentLoading = false
            this.paymentOpen = false
            this.$modal.msgSuccess("打款完成");
            this.$refs['payslipDetailRef'].getList();
          }).catch(() => {
            this.paymentLoading = false
          });
        }
      })

    }
  },
  watch:{
    payslipId:{
      handler(val){
        this.handlePayslip(val)
      }
      ,immediate:true
    }
  }
}
</script>
<style scoped lang="scss">
.mb8{
  margin-top: 20px;
}
</style>
